<template>
  <div class="goodesmodelbox">
    <el-dialog
      :showClose="false"
      :title="getTitleHandle(enterType)"
      :visible.sync="centerDialogVisible"
      height="100%"
      top
      width="100%"
      :fullscreen="true"
      v-loading="loading"
    >
      <el-form
        ref="ruleForm"
        :model="ActiveInfo"
        :rules="rules"
        class="demo-ruleForm"
        label-width="200px"
        :disabled="alldisable"
      >
        <el-form-item
          label="活动名称"
          placeholder="请输入活动名称"
          prop="activeName"
        >
          <el-input v-model="ActiveInfo.activeName"></el-input>
        </el-form-item>

        <div v-if="flashDisable">
          <el-form-item label="是否满减" prop="conditionType">
            <el-radio-group v-model="ActiveInfo.conditionType">
              <el-radio :label="1">满金额</el-radio>
              <!-- <el-radio :label="2">满件</el-radio> -->
            </el-radio-group>
          </el-form-item>
          <el-form-item label="满减活动">
            <div class="ManJan">
              <div>
                <el-button
                  :disabled="tpdisable"
                  type="primary"
                  icon="el-icon-plus"
                  circle
                  @click="addDomain"
                ></el-button>
              </div>
              <div>满</div>
              <div>减</div>
            </div>
          </el-form-item>
          <el-form-item
            label=""
            v-if="this.ActiveInfo.activeConditions.length === 0"
            prop="activeConditions"
          >
            <div class="ManJanEmpty">
              <el-empty :image-size="100"></el-empty>
            </div>
          </el-form-item>
          <el-form-item v-else class="ManJanItemBox">
            <div
              v-for="(domain, index) in this.ActiveInfo.activeConditions"
              :key="domain.key"
              class="ManJanItem"
            >
              <div
                @mouseover="mouseover(index)"
                @mouseleave="mouseleave(index)"
              >
                <div v-if="delectdiv !== index">{{ index + 1 }}</div>
                <div v-if="delectdiv === index">
                  <el-button
                    :disabled="tpdisable"
                    type="danger"
                    icon="el-icon-delete"
                    @click.prevent="removeDomain(domain)"
                    circle
                  ></el-button>
                </div>
              </div>

              <div>
                <el-input
                  :style="{ width: '300px' }"
                  v-model="domain.activeCondition"
                  placeholder="请输入 满"
                  :disabled="tpdisable"
                ></el-input>
              </div>
              <div>
                <el-input
                  :style="{ width: '300px' }"
                  v-model="domain.activeAmount"
                  placeholder="请输入 减"
                  :disabled="tpdisable"
                ></el-input>
              </div>
            </div>
          </el-form-item>
        </div>

        <el-form-item label="活动时间范围" prop="startTime">
          <el-date-picker
            :disabled="tpdisable"
            style="width: 600px"
            v-model="chooseTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="chooseTimeHandle"
            :picker-options="{
              disabledDate(time) {
                return time.getTime() < Date.now() - 8.64e7;
              },
            }"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="PC活动横幅" class="PCItem" prop="pcBannerSrc">
          <div v-if="this.enterType !== 3 && this.enterType !== 5">
            <el-upload
              :class="{ uploadBox_hide: hideUploadEdit }"
              :key="uploadKey"
              :action="uploadURL"
              :file-list="fileList"
              list-type="picture-card"
              :show-file-list="true"
              :auto-upload="true"
              :on-success="picturesuccess"
              :before-upload="picturebefore"
              :on-error="pictureerror"
              :on-exceed="pictureexceed"
              :on-change="handleEditChange"
              :limit="1"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{ file }">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.imgUrl"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </div>
          <div v-else>
            <el-image
              style="width: 100px; height: 100px"
              :src="fileList[0]"
              :preview-src-list="fileList"
            >
            </el-image>
          </div>
        </el-form-item>
        <!-- <el-form-item label="H5活动横幅" prop="h5BannerSrc" class="HItem">
          <div v-if="this.enterType !== 3">
            <el-upload
              :class="{ uploadBox_hide: hideUploadEdit2 }"
              :key="uploadKey2"
              :action="uploadURL"
              :file-list="fileList2"
              list-type="picture-card"
              :show-file-list="true"
              :auto-upload="true"
              :on-success="picturesuccess2"
              :before-upload="picturebefore2"
              :on-error="pictureerror2"
              :on-exceed="pictureexceed2"
              :on-change="handleEditChange2"
              :limit="1"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{ file }">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.imgUrl"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-delete"
                    @click="handleRemove2(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </div>
          <div v-else>
            <el-image
              style="width: 100px; height: 100px"
              :src="fileList2[0]"
              :preview-src-list="fileList2"
            >
            </el-image>
          </div>
        </el-form-item> -->
        <el-form-item label="活动说明" prop="notes">
          <el-input
            type="textarea"
            placeholder="请输入活动说明"
            v-model="ActiveInfo.notes"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelgoodesmodel">取 消</el-button>
        <el-button
          :disabled="alldisable"
          type="primary"
          @click="saveActiveHandle"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { cloud } from "@/framework/utils/request";
import {
  AddActiveFun,
  WatchActiveInfo,
  EditActiveFun,
} from "@/api/mallApi/managementend/marketing";

export default {
  name: "NewActivity",
  components: {},
  props: {
    centerDialogVisible: Boolean,
    currentRow: Object,
    enterType: Number,
    cancelSubmit: Number,
  },
  data() {
    return {
      flashDisable: true,
      alldisable: false,
      tpdisable: false,
      loading: false,
      hideUploadEdit: false,
      hideUploadEdit2: false,
      uploadKey: 0,
      fileList: [],
      uploadKey2: 0,
      fileList2: [],
      dialogImageUrl: "",
      dialogVisible: false,
      uploadURL:
        process.env.VUE_APP_BASE_API +
        cloud.file +
        "/sysFileInfo/upload?secretFlag=N&fileBucket=mall",
      delectdiv: -100,
      chooseTime: null,
      ActiveInfo: {
        mallCode: "",
        activeName: "",
        isOpen: 1,
        startTime: "",
        endTime: "",
        activityCategory: 1,
        pcBannerSrc: "",
        h5BannerSrc: "",
        notes: "",
        conditionType: 1,
        activeConditions: [
          // { activeCondition: null, activeAmount: null }
        ],
      },
      rules: {
        activeName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          {
            min: 2,
            max: 25,
            message: "长度在 2 到 25 个字符",
            trigger: "blur",
          },
        ],
        conditionType: [{ required: true, trigger: "blur" }],
        activeConditions: [
          {
            required: true,
            message: "请输入活动满减条件,Number类型，满应该大于减，且不为空！",
            trigger: "blur",
          },
        ],
        startTime: [
          { required: true, message: "请选择活动时间", trigger: "blur" },
        ],
        pcBannerSrc: [
          { required: true, message: "请上传PC活动横幅图片", trigger: "blur" },
        ],
        // h5BannerSrc: [
        //   { required: true, message: "请上传H5活动横幅图片", trigger: "blur" },
        // ],
        notes: [{ required: true, message: "请输入活动说明", trigger: "blur" }],
      },
    };
  },
  methods: {
    saveActiveHandle() {
      if (this.enterType === 1) {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            const isValid = this.ActiveInfo.activeConditions.every(
              (condition) => {
                // 检查 activeCondition 和 activeAmount 是否为空或者为汉字，并且 activeCondition 大于 activeAmount
                return (
                  condition.activeCondition !== null &&
                  condition.activeCondition !== "" &&
                  // isNaN(Number(condition.activeCondition)) &&
                  condition.activeAmount !== null &&
                  condition.activeAmount !== "" &&
                  // isNaN(Number(condition.activeAmount)) &&
                  Number(condition.activeCondition) >
                    Number(condition.activeAmount)
                );
              }
            );
            // 如果不满足条件，弹出提示框
            if (!isValid && this.ActiveInfo.activeConditions.length === 0) {
              this.$message({
                message: "请正确输入活动满减条件！",
                type: "warning",
              });
              return;
            }
            this.ActiveInfo.activeConditions =
              this.ActiveInfo.activeConditions.map((item) => {
                return {
                  activeCondition:
                    item.activeCondition !== null
                      ? item.activeCondition * 100
                      : null,
                  activeAmount:
                    item.activeAmount !== null ? item.activeAmount * 100 : null,
                };
              });
            this.loading = true;
            AddActiveFun(this.ActiveInfo)
              .then((res) => {
                if (res.code !== "00000") return;
                this.loading = false;
                this.$message({
                  message: "活动创建成功！",
                  type: "success",
                });
                this.cancelgoodesmodel();
                this.$emit("Refresh");
              })
              .catch((err) => {
                this.loading = false;
                console.log(err);
              });
          } else {
            this.$message({
              message: "请补全活动信息！",
              type: "warning",
            });
            return false;
          }
        });
      } else if (this.enterType === 2) {
        delete this.ActiveInfo.activeAttribution;
        delete this.ActiveInfo.activeCode;
        this.ActiveInfo.activeConditions = this.ActiveInfo.activeConditions.map(
          (item) => {
            return {
              activeCondition:
                item.activeCondition !== null
                  ? item.activeCondition * 100
                  : null,
              activeAmount:
                item.activeAmount !== null ? item.activeAmount * 100 : null,
            };
          }
        );
        this.loading = true;
        EditActiveFun(this.ActiveInfo)
          .then((res) => {
            if (res.code !== "00000") return;
            this.loading = false;
            this.$message({
              message: "活动编辑成功！",
              type: "success",
            });
            this.cancelgoodesmodel();
            this.tpdisable = false;
            this.$emit("Refresh");
          })
          .catch((err) => {
            this.loading = false;
            console.log(err);
          });
      } else if (this.enterType === 3) {
        this.cancelgoodesmodel();
        this.alldisable = false;
      } else if (this.enterType === 4) {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.ActiveInfo.activeConditions =
              this.ActiveInfo.activeConditions.map((item) => {
                return {
                  activeCondition:
                    item.activeCondition !== null
                      ? item.activeCondition * 100
                      : null,
                  activeAmount:
                    item.activeAmount !== null ? item.activeAmount * 100 : null,
                };
              });
            this.loading = true;
            this.ActiveInfo.activityCategory = 2;
            AddActiveFun(this.ActiveInfo)
              .then((res) => {
                if (res.code !== "00000") return;
                this.loading = false;
                this.$message({
                  message: "活动创建成功！",
                  type: "success",
                });
                this.cancelgoodesmodel();
                this.$emit("Refresh");
              })
              .catch((err) => {
                this.loading = false;
                console.log(err);
              });
          } else {
            this.$message({
              message: "请补全活动信息！",
              type: "warning",
            });
            return false;
          }
        });
      } else if (this.enterType === 6) {
        delete this.ActiveInfo.activeAttribution;
        delete this.ActiveInfo.activeCode;
        this.ActiveInfo.activeConditions = this.ActiveInfo.activeConditions.map(
          (item) => {
            return {
              activeCondition:
                item.activeCondition !== null
                  ? item.activeCondition * 100
                  : null,
              activeAmount:
                item.activeAmount !== null ? item.activeAmount * 100 : null,
            };
          }
        );
        this.loading = true;
        EditActiveFun(this.ActiveInfo)
          .then((res) => {
            if (res.code !== "00000") return;
            this.loading = false;
            this.$message({
              message: "活动编辑成功！",
              type: "success",
            });
            this.cancelgoodesmodel();
            this.tpdisable = false;
            this.$emit("Refresh");
          })
          .catch((err) => {
            this.loading = false;
            console.log(err);
          });
      }
    },
    chooseTimeHandle(e) {
      if (e !== null && this.chooseTime !== null) {
        this.ActiveInfo.startTime = e[0];
        this.ActiveInfo.endTime = e[1];
      } else {
        this.ActiveInfo.startTime = "";
        this.ActiveInfo.endTime = "";
      }
    },
    mouseover(index) {
      this.delectdiv = index;
    },
    mouseleave(index) {
      this.delectdiv = -100; // 设置一个不可能的值来确保按钮被隐藏
    },
    removeDomain(item) {
      var index = this.ActiveInfo.activeConditions.indexOf(item);
      if (index !== -1) {
        this.ActiveInfo.activeConditions.splice(index, 1);
      }
    },
    addDomain() {
      this.ActiveInfo.activeConditions.push({
        activeAmount: "",
      });
    },
    getTitleHandle(type) {
      switch (type) {
        case 1:
          return "新增活动";
        case 2:
          return "编辑活动";
        case 3:
          return "查看活动";
        case 4:
          return "新增活动";
        case 5:
          return "查看活动";
        case 6:
          return "编辑活动";
        default:
          return "未知";
      }
    },
    cancelgoodesmodel() {
      this.$emit("cancelgoodesmodel", false);
      this.alldisable = false;
      this.tpdisable = false;
    }, // 取消按钮 传值
    //图片上传
    // on-change添加文件，上传成功和上传失败时都会被调用
    handleEditChange(file, fileList) {
      this.hideUploadEdit = this.fileList.length >= fileList.length;
    },
    handleEditChange2(file, fileList) {
      this.hideUploadEdit2 = this.fileList2.length >= fileList.length;
    },
    picturesuccess(response, file, fileList) {
      file.imgUrl = response.data.fileUrl;
      this.ActiveInfo.pcBannerSrc = response.data.fileUrl;
      this.fileList.push({
        imgUrl: response.data.fileUrl,
      });
    },
    picturesuccess2(response, file, fileList) {
      file.imgUrl = response.data.fileUrl; ///???????????
      this.ActiveInfo.h5BannerSrc = response.data.fileUrl;
      this.fileList2.push({
        imgUrl: response.data.fileUrl,
      });
    },
    pictureerror(response, file, fileList) {},
    pictureerror2(response, file, fileList) {},
    picturebefore(file) {
      const isJPG = file.type === "image/jpeg" || "image/png" || "image/jpg";
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPEG,JPG,PNG 格式!");
      }
      if (!isLt10M) {
        this.$message.error("上传图片大小不能超过10MB!");
      }
      this.uploadKey += 1;
      return isJPG && isLt10M;
    }, //图片大小格式校验
    picturebefore2(file) {
      const isJPG = file.type === "image/jpeg" || "image/png" || "image/jpg";
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPEG,JPG,PNG 格式!");
      }
      if (!isLt10M) {
        this.$message.error("上传图片大小不能超过10MB!");
      }
      this.uploadKey2 += 1;
      return isJPG && isLt10M;
    }, //图片大小格式校验
    pictureexceed(files, fileList) {
      if (fileList.length >= 4) {
        this.$message.error("图片最多上传1张!");
      }
    }, //图片限制提示\
    pictureexceed2(files, fileList) {
      if (fileList.length >= 4) {
        this.$message.error("图片最多上传1张!");
      }
    }, //图片限制提示
    handleRemove(file) {
      // 移除图片
      const index = this.fileList.indexOf(file);
      if (index !== -1) {
        this.fileList.splice(index, 1);
      }
      this.hideUploadEdit = !(this.fileList.length === 0);
    },
    handleRemove2(file) {
      // 移除图片
      const index = this.fileList2.indexOf(file);
      if (index !== -1) {
        this.fileList2.splice(index, 1);
      }
      this.hideUploadEdit2 = !(this.fileList2.length === 0);
    },
    clearImages() {
      // 清空图片列表
      this.fileList = [];
    },
    clearImages2() {
      // 清空图片列表
      this.fileList2 = [];
    },
  },
  mounted() {},
  created() {
    console.log("created", this.enterType);
    if (this.enterType === 2) {
      this.tpdisable = true;
      this.loading = true;
      const param = {
        id: this.currentRow.id,
      };
      WatchActiveInfo(param)
        .then((res) => {
          if (res.code !== "00000") return;
          this.ActiveInfo = res.data;
          this.chooseTime = [res.data.startTime, res.data.endTime];
          this.ActiveInfo.conditionType = 1;
          this.ActiveInfo.activeConditions =
            this.ActiveInfo.activeConditions.map((item) => {
              return {
                activeCondition:
                  item.activeCondition !== null
                    ? item.activeCondition / 100
                    : null,
                activeAmount:
                  item.activeAmount !== null ? item.activeAmount / 100 : null,
              };
            });
          this.fileList.push({
            imgUrl: res.data.pcBannerSrc,
          });
          this.hideUploadEdit = this.fileList.length >= 1;
          this.fileList2.push({
            imgUrl: res.data.h5BannerSrc,
          });
          this.hideUploadEdit2 = this.fileList2.length >= 1;
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          console.log(err);
        });
    } else if (this.enterType === 3) {
      this.alldisable = true;
      this.tpdisable = true;
      this.loading = true;
      const param = {
        id: this.currentRow.id,
      };
      WatchActiveInfo(param)
        .then((res) => {
          if (res.code !== "00000") return;
          this.ActiveInfo = res.data;
          this.chooseTime = [res.data.startTime, res.data.endTime];
          this.ActiveInfo.conditionType = 1;
          this.ActiveInfo.activeConditions =
            this.ActiveInfo.activeConditions.map((item) => {
              return {
                activeCondition:
                  item.activeCondition !== null
                    ? item.activeCondition / 100
                    : null,
                activeAmount:
                  item.activeAmount !== null ? item.activeAmount / 100 : null,
              };
            });
          this.fileList = [res.data.pcBannerSrc];
          this.fileList2 = [res.data.h5BannerSrc];
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          console.log(err);
        });
    } else if (this.enterType === 4) {
      this.flashDisable = false;
    } else if (this.enterType === 5) {
      this.flashDisable = false;
      this.alldisable = true;
      this.tpdisable = true;
      this.loading = true;
      const param = {
        id: this.currentRow.id,
      };
      WatchActiveInfo(param)
        .then((res) => {
          if (res.code !== "00000") return;
          this.ActiveInfo = res.data;
          this.chooseTime = [res.data.startTime, res.data.endTime];
          this.ActiveInfo.conditionType = 1;
          this.fileList = [res.data.pcBannerSrc];
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          console.log(err);
        });
    } else if (this.enterType === 6) {
      this.flashDisable = false;
      this.tpdisable = true;
      this.loading = true;
      const param = {
        id: this.currentRow.id,
      };
      WatchActiveInfo(param)
        .then((res) => {
          if (res.code !== "00000") return;
          this.ActiveInfo = res.data;
          this.chooseTime = [res.data.startTime, res.data.endTime];
          this.ActiveInfo.conditionType = 1;
          this.ActiveInfo.activeConditions =
            this.ActiveInfo.activeConditions.map((item) => {
              return {
                activeCondition:
                  item.activeCondition !== null
                    ? item.activeCondition / 100
                    : null,
                activeAmount:
                  item.activeAmount !== null ? item.activeAmount / 100 : null,
              };
            });
          this.fileList.push({
            imgUrl: res.data.pcBannerSrc,
          });
          this.hideUploadEdit = this.fileList.length >= 1;
          this.fileList2.push({
            imgUrl: res.data.h5BannerSrc,
          });
          this.hideUploadEdit2 = this.fileList2.length >= 1;
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          console.log(err);
        });
    }
  },
  watch: {
    centerDialogVisible(newVal) {
      // 监听 centerDialogVisible 的变化
      if (!newVal) {
        // 当 centerDialogVisible 变为 false 时触发事件
        this.$emit("close-dialog");
      }
    },
  },
};
</script>

<style lang="scss">
.goodesmodelbox {
  .PCItem {
    .uploadBox_hide .el-upload--picture-card {
      display: none;
    }
  }
  .HItem {
    .uploadBox_hide .el-upload--picture-card {
      display: none;
    }
  }
  .ManJanEmpty {
    width: 800px;
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    border: 2px solid #ebeef5;
    border-top: none;
    margin-top: -25px;
    .el-empty__description {
      text-align: center;
    }
  }
  .ManJan {
    width: 800px;
    height: 50px;
    display: flex;
    background-color: #fafafa;
    border: 2px solid #ebeef5;
    > div:nth-child(1) {
      width: 50px;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: space-around;
      border-right: 2px solid #ebeef5;
    }
    > div:nth-child(2) {
      width: 400px;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: space-around;
      border-right: 2px solid #ebeef5;
    }
    > div:nth-child(3) {
      width: 400px;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: space-around;
    }
  }
  .ManJanItemBox {
    margin-top: -25px;
    .ManJanItem {
      width: 800px;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: space-around;
      border-bottom: 2px solid #ebeef5;
      > div:nth-child(1) {
        width: 50px;
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: space-around;
        border-right: 2px solid #ebeef5;
        border-left: 2px solid #ebeef5;
      }
      > div:nth-child(2) {
        width: 400px;
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: space-around;
        border-right: 2px solid #ebeef5;
      }
      > div:nth-child(3) {
        width: 400px;
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: space-around;
        border-right: 2px solid #ebeef5;
      }
    }
  }
}
</style>
